package com.gyh.system.scheduler.utils;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSONObject;
import com.gyh.system.common.utils.SpringContextHolder;
import com.gyh.system.scheduler.entity.ScheduleJob;
import com.gyh.system.scheduler.entity.ScheduleJobLog;
import com.gyh.system.scheduler.service.ScheduleJobLogService;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月6日 上午1:28:31
* 
*/
public class ScheduleJobExecuter extends QuartzJobBean{

	private Logger logger = LoggerFactory.getLogger(getClass());
	private ExecutorService service = Executors.newSingleThreadExecutor();
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		String jsonJob = context.getMergedJobDataMap().getString("JOB_PARAM_KEY");
		ScheduleJob scheduleJob =  JSONObject.parseObject(jsonJob, ScheduleJob.class);
		
		ScheduleJobLogService scheduleJobLogService = SpringContextHolder.getBean(ScheduleJobLogService.class);
		
		ScheduleJobLog log = new ScheduleJobLog();
		log.setJobId(scheduleJob.getId());
		log.setBeanName(scheduleJob.getBeanName());
		log.setMethodName(scheduleJob.getMethodName());
		log.setParams(scheduleJob.getParams());
		
		//任务执行开始
		long startTime = System.currentTimeMillis();

		try {
			
			logger.info("job 准备执行，job的ID："+scheduleJob.getId());
			ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
			Future<?> future = service.submit(task);
			future.get();
			
			long times = System.currentTimeMillis() - startTime;
			log.setTimes(times);
			log.setStatus(0);
			logger.info("任务执行完成，Job的name："+scheduleJob.getJobName()+"    总共耗时："+times+" 毫秒");
		} catch (Exception e) {
			logger.info("任务执行失败，Job的name："+scheduleJob.getJobName());
			long times = System.currentTimeMillis() - startTime;
			log.setStatus(1);
			log.setTimes(times);
			log.setError(StringUtils.substring(e.toString(), 0, 2000));
		} finally {
			log.setCreateTime(new Date());
			scheduleJobLogService.insert(log);
		}
		
		
	}

}
